import {createStore} from '@/airstore';
import ApiClient from '@/services/apiClient';

function transformPwdTask(trd) {
  return {
    id: trd.TS_TasktTid,
    airplane_no: trd.MpDp_Acno, //机号
    flight_no: trd.VF_FlightID_Next, //航班号
    est_depart_date: trd.VF_ETD_Next, // 预计起飞
    release_by: trd.PassPer, //放行人员
    workers: trd.WorkPer, //工作者
    airport: trd.VF_DepartureAirport_Next, //站点
    preflight: trd.VF_FlightID, //前序航班
    postflight: trd.VF_FlightID_Next, //后序航班
    status: trd.LTP_PowerStatus, //状态
    statusDes: translataPowerStatus(trd.LTP_PowerStatus), //状态
    operPer: trd.LTP_OperPer, //确认人
    operTime: trd.LTP_OperTime, //确认时间
    checked: false,
  };
}

function translataPowerStatus(vs) {
  if (vs === 2) {
    return '已确认上电';
  } else {
    return '待确认上电';
  }
}

export default createStore({
  namespace: 'PowerupStore',
  pwuUnConfirmTasks: [],
  pwuConfirmTasks: [],
  setPwuTasks(tsData) {
    this.pwuUnConfirmTasks = tsData[1].map(transformPwdTask);
    this.pwuConfirmTasks = tsData[0].map(transformPwdTask);
  },
  checkUnconfrimTask(tsId, checked) {
    this.pwuUnConfirmTasks = this.pwuUnConfirmTasks.map((pwt) => {
      if (pwt.id === tsId) {
        return {...pwt, checked};
      }
      return pwt;
    });
  },
  async getPuTasks(loginName) {
    const srRes = await ApiClient.post('zoController/v1/getLongTrPower', {
      loginUser: loginName,
    });
    if (!srRes.errorCode) {
      this.setPwuTasks(srRes.data);
    }
    return srRes;
  },
  placeConfirmTs(ids) {
    this.pwuUnConfirmTasks = this.pwuUnConfirmTasks.filter(
      (pwt) => pwt.checked,
    );
    this.pwuConfirmTasks = this.pwuUnConfirmTasks
      .filter((pwt) => ids.indexOf(pwt.id) !== -1)
      .map((pwt) => ({...pwt, status: 2, checked: false}))
      .concat(this.pwuConfirmTasks);
  },
  async confirmLongPowerItems(loginName) {
    const ids = this.pwuUnConfirmTasks
      .filter((pwuct) => pwuct.checked)
      .map((pwu) => pwu.id);
    const cfmRes = await ApiClient.post('zoController/v1/ltpOnPower', {
      loginUser: loginName,
      jsonResult: ids.join(','),
    });
    if (!cfmRes.errorCode) {
      this.placeConfirmTs(ids);
    }
    return cfmRes;
  },
});
